package com.test.springmvc.crud.dao;

import com.test.springmvc.crud.entities.Department;
import com.test.springmvc.crud.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/10/13 10:49
 */
@Repository
public class EmployeeDao {
    private static Map<Integer, Employee> employeeMap = null;
    private static int initId = 1006;

    static {
        employeeMap = new HashMap<>();
        employeeMap.put(1001, new Employee(1001, "aa", "aa@123.com", 1, new Department(101, "D-AA")));
        employeeMap.put(1002, new Employee(1002, "bb", "bb@123.com", 1, new Department(102, "D-BB")));
        employeeMap.put(1003, new Employee(1003, "cc", "cc@123.com", 0, new Department(103, "D-CC")));
        employeeMap.put(1004, new Employee(1004, "dd", "dd@123.com", 0, new Department(104, "D-DD")));
        employeeMap.put(1005, new Employee(1005, "ee", "ee@123.com", 1, new Department(105, "D-EE")));
    }

    @Autowired
    private DepartmentDao departmentDao;

    public Collection<Employee> getEmployees() {
        return employeeMap.values();
    }

    public Employee getEmployee(Integer id) {
        return employeeMap.get(id);
    }

    public void delete(Integer id) {
        employeeMap.remove(id);
    }

    public void save(Employee employee) {
        if (employee.getId() == null) {
            employee.setId(initId++);
        }
        employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
        employeeMap.put(employee.getId(), employee);
    }
}
